package com.matriq.cloudmanager.fragment;

import java.util.List;

import com.matriq.cloudmanager.R;
import com.matriq.cloudmanager.dialog.ConfirmDialog;
import com.matriq.cloudmanager.entity.ComComment;
import com.matriq.cloudmanager.entity.TypeComComment;
import com.matriq.cloudmanager.service.AccountService;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import net.lgpage.dialog.DialogListener;
import net.lgpage.fragment.BaseFragment;
import net.lgpage.http.ExceptionAsyncTask;
import net.lgpage.http.HttpMsg;
import net.lgpage.http.SwipeRefeshAsyncTask;
import net.lgpage.util.Checker.StringUtils;
import net.lgpage.util.Cleaner;

public class ZhpjFragment extends BaseFragment {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fm_zhpj, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		setViews();
		setEvents();
		loadData();
	}

	android.support.v4.widget.SwipeRefreshLayout srl;
	LinearLayout ll_rcy;
	Button bt_confirm;
	LinearLayout ll_nothing;
	TextView tv_nothing;

	private void setViews() {
		srl = (android.support.v4.widget.SwipeRefreshLayout) getView().findViewById(R.id.srl);
		ll_rcy = (LinearLayout) getView().findViewById(R.id.ll_rcy);
		bt_confirm = (Button) getView().findViewById(R.id.bt_confirm);
		ll_nothing = (LinearLayout) getView().findViewById(R.id.ll_nothing);
		tv_nothing = (TextView) getView().findViewById(R.id.tv_nothing);
		rcy_adp = new RcyAdp();
	}

	private void setEvents() {
		srl.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				refeshRcyList();
			}
		});
		setNotingEvents();
	}

	private void setNotingEvents() {
		ll_nothing.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				changeListState(false);
				refeshRcyList();
			}
		});
	}

	private void checkListNoting() {
		if (rcylist == null || rcylist.size() == 0) {
			changeListState(true);
		} else {
			changeListState(false);
		}
	}

	private void changeListState(boolean isnothing) {
		if (!isnothing) {
			ll_nothing.setVisibility(View.GONE);
			srl.setVisibility(View.VISIBLE);
		} else {
			ll_nothing.setVisibility(View.VISIBLE);
			srl.setVisibility(View.GONE);
		}
	}

	private class RcyViewHolder extends RecyclerView.ViewHolder {
		TextView tv;
		RadioGroup rg;
		EditText et;
		RadioButton rb[] = new RadioButton[4];

		public RcyViewHolder(View view) {
			super(view);
		}
	}

	RcyAdp rcy_adp;

	class RcyAdp extends RecyclerView.Adapter<RcyViewHolder> {

		LayoutParams lp;

		@Override
		public int getItemCount() {
			if (rcylist == null)
				return 0;
			return rcylist.size();
		}

		public void notifyDataChange() {
			ll_rcy.removeAllViews();
			for (int i = 0; i < getItemCount(); i++) {
				RcyViewHolder h = onCreateViewHolder(null, i);
				ll_rcy.addView(h.itemView);
				onBindViewHolder(h, i);
			}
			ll_rcy.addView(bt_confirm);
		}

		public RcyAdp() {
			super();
			lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		}

		@Override
		public void onBindViewHolder(final RcyViewHolder h, final int position) {
			final ComComment obj = rcylist.get(position);
			h.tv.setText(obj.getTitle());
			String ans = obj.getAns();
			if(StringUtils.isEmpty(ans)){
				ans = obj.getAn();
			}
			List<String> list = obj.getItems();
			h.rg.clearCheck();
			if (list != null && list.size() > 0) {
				for (int i = 0; i < h.rb.length; i++) {
					if (i < list.size()) {
						String item = list.get(i);
						h.rb[i].setText(item);
						if(type == 1){
							if (item.equals(ans)) {
								h.rg.check(h.rb[i].getId());
							} else {
								// h.rb[i].setChecked(false);
							}
						}else{
							try {
								int ai = Integer.parseInt(ans);
								ai = ai-1;
								if(ai == i){
									h.rg.check(h.rb[i].getId());
								}
							} catch (NumberFormatException e) {
							}
						}
						h.rb[i].setVisibility(View.VISIBLE);
					} else {
						// h.rb[i].setChecked(false);
						h.rb[i].setVisibility(View.GONE);
					}
				}
			}
			if ("1".equals(obj.getTtype())) {
				h.rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						switch (checkedId) {
						case R.id.rb0:
							obj.setAns(h.rb[0].getText().toString());
							break;
						case R.id.rb1:
							obj.setAns(h.rb[1].getText().toString());
							break;
						case R.id.rb2:
							obj.setAns(h.rb[2].getText().toString());
							break;
						case R.id.rb3:
							obj.setAns(h.rb[3].getText().toString());
							break;
						default:
							break;
						}
					}
				});
			}else{
				h.et.setText(ans);
			}
			h.et.addTextChangedListener(new TextWatcher() {

				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {
					obj.setAns(s.toString());
				}

				@Override
				public void beforeTextChanged(CharSequence s, int start, int count, int after) {
					
				}

				@Override
				public void afterTextChanged(Editable s) {

				}
			});
			if ("1".equals(obj.getTtype())) {
				h.et.setVisibility(View.GONE);
				h.rg.setVisibility(View.VISIBLE);
			} else {
				h.rg.setVisibility(View.GONE);
				h.et.setVisibility(View.VISIBLE);
			}
			if (type == 1) {
				h.rg.setEnabled(true);
				h.et.setEnabled(true);
				h.rg.setClickable(true);
				h.et.setHint("请输入你的回答");
			} else {
				h.rg.setEnabled(false);
				for(int i =0;i<h.rb.length;i++){
					h.rb[i].setClickable(false);
					h.rb[i].setEnabled(false);
				}
				h.et.setEnabled(false);
				h.et.setBackgroundResource(R.color.transparent);
				h.et.setHint("");
				h.et.setMinLines(2);
				h.rg.setClickable(false);
			}
		}

		@Override
		public RcyViewHolder onCreateViewHolder(ViewGroup vgp, final int position) {
			View cv = getActivity().getLayoutInflater().inflate(R.layout.rcy_zhpj, null);
			cv.setLayoutParams(lp);
			RcyViewHolder h = new RcyViewHolder(cv);
			h.tv = (TextView) cv.findViewById(R.id.tv);
			h.rg = (RadioGroup) cv.findViewById(R.id.rg);
			h.et = (EditText) cv.findViewById(R.id.et);
			h.rb[0] = (RadioButton) cv.findViewById(R.id.rb0);
			h.rb[1] = (RadioButton) cv.findViewById(R.id.rb1);
			h.rb[2] = (RadioButton) cv.findViewById(R.id.rb2);
			h.rb[3] = (RadioButton) cv.findViewById(R.id.rb3);
			return h;
		}
	}

	private boolean checkEts() {
		if (rcylist == null)
			return false;
		for (int i = 0; i < rcylist.size(); i++) {
			ComComment obj = rcylist.get(i);
			if (StringUtils.isEmpty(obj.getAns())) {
				if ("1".equals(obj.getTtype())) {
					toast("第" + (i + 1) + "题尚未选择");
					return false;
				} else {
					//toast("第" + (i + 1) + "题尚未填写");
				}
			}
		}
		return true;
	}

	List<ComComment> rcylist;
	int type = 0;
	RcyListTask rcylistTask;

	public void refeshRcyList() {
		if (rcylistTask != null) {
			rcylistTask.cancel(true);
		}
		rcylistTask = new RcyListTask(getActivity());
		rcylistTask.setSwipeLayout(srl);
		rcylistTask.execute();
	}

	private class RcyListTask extends SwipeRefeshAsyncTask<TypeComComment> {

		public RcyListTask(Context context) {
			super(context);
		}

		@Override
		public TypeComComment doInBackgroundX(String... params) throws Exception {
			return AccountService.getService().com_comment();
		}

		@Override
		public void onPostExecuteX(TypeComComment result) {
			if (result == null) {
				return;
			} else {
				type = result.getType();
				if (type == 1) {
					bt_confirm.setText("提交");
					bt_confirm.setEnabled(true);
					bt_confirm.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							if (checkEts()) {
								ConfirmDialog dg = new ConfirmDialog(getActivity());
								dg.setData("评价后不可修改，是否继续提交？");
								dg.setListener(new DialogListener() {
									
									@Override
									public void onDialogExecute(Object... obj) {
										putObj();
									}
								});
								dg.show();
							}
						}
					});
				} else if(type == 2){
					bt_confirm.setText("已评价");
					bt_confirm.setEnabled(false);
				}else{
					bt_confirm.setText("当前时间无法评价");
					bt_confirm.setEnabled(false);
				}
				if (rcylist != null && rcylist.size() > 0) {
					for (int i = 0; i < rcylist.size() && i < result.getCon().size(); i++) {
						result.getCon().get(i).setAns(rcylist.get(i).getAns());
					}
				}
				rcylist = result.getCon();
				checkListNoting();
				rcy_adp.notifyDataChange();
			}
		}
	}

	ObjTask objTask;

	public void putObj() {
		if (objTask != null) {
			objTask.cancel(true);
		}
		objTask = new ObjTask(getActivity());
		objTask.execute();
	}

	private class ObjTask extends ExceptionAsyncTask<HttpMsg> {

		public ObjTask(Context context) {
			super(context);
		}

		@Override
		public HttpMsg doInBackgroundX(String... params) throws Exception {
			return AccountService.getService().com_commit(rcylist);
		}

		@Override
		public void onPostExecuteX(HttpMsg result) {
			if (result == null) {
				return;
			} else {
				getActivity().setResult(200);
				getActivity().finish();
			}
		}
	}

	private void loadData() {

		refeshRcyList();
	}

	@Override
	public void onDestroy() {
		Cleaner.cleanTask(rcylistTask, objTask);
		super.onDestroy();
	}

}